package com.gf.gf_data.sys.redis;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * redis实现共享session操作dao接口
 * Created by yxl on 2017/12/19
 */
@Component
public class RedisSessionDAO extends EnterpriseCacheSessionDAO {

    private static Logger log = LoggerFactory.getLogger(RedisSessionDAO.class);

    /**
     *  session过期时间:1800（s）
     */
    private static int expireTime = 1800;

    /**
     * 缓存前缀
     */
    private static String prefix = "redis-shiro-session:";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 创建session保存到redis
     */
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        log.debug("Create session :{}", session.getId());
        redisTemplate.opsForValue().set(prefix + sessionId.toString(), session);
        return sessionId;
    }

    /**
     * 读取session
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        log.debug("Read session :{}", sessionId);
        // 从缓存中获取session
        Session session = super.doReadSession(sessionId);
        // 缓存中没有，则从redis获取
        if (session == null)
            session = (Session) redisTemplate.opsForValue().get(prefix + sessionId.toString());
        return session;
    }

    /**
     * 更新seesion最后一次访问时间
     */
    @Override
    protected void doUpdate(Session session) {
        log.debug("Update session :{}", session.getId());
        super.doUpdate(session);
        String key = prefix + session.getId().toString();
        if (!redisTemplate.hasKey(key))
            redisTemplate.opsForValue().set(key, session);
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    }

    /**
     * 删除seesion
     */
    @Override
    protected void doDelete(Session session) {
        log.debug("Delete session :{}", session.getId());
        super.doDelete(session);
        redisTemplate.delete(prefix + session.getId().toString());
    }
}
